<template>

<el-card class="box-card">
  <el-row :gutter="12">
  <el-col :span="8">
  <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 搜索框 -->
  <el-input
   v-model="user_data.queryName"
   placeholder="输入要搜索的账号"
   class="input-with-select"
   
  >
   <template #append>
    <el-button :icon="Search" @click="searchUser" />
   </template>
  </el-input>
  </el-col>
  <el-col :span="1">
    <el-button type="primary" :icon="CirclePlus" class="adduser-button" @click="dialogFormVisible=true" >增加用户</el-button>
  </el-col>
  <el-table :data="user_data.tableData" stripe class="table" width="180">
    <el-table-column prop="id" label="id" width="180" />
    <el-table-column prop="name" label="账号" width="180" />
    <el-table-column prop="nick_name" label="昵称" />
    <el-table-column prop="phone" label="手机号" />
    <el-table-column prop="email" label="邮箱" />
    <!-- 修改操作 -->
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>

        <el-button
          size="small"
          type="success"
          @click="handleRest(scope.$index, scope.row)"
        >
          重置密码
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  </el-row>
  <!-- 分页 -->
  <el-pagination
   v-model:current-page="user_data.pageNum"
   v-model:page-size="user_data.pageSize"
   :page-sizes="pagesize"
   :small="small"
   :disabled="disabled"
   :background="background"
   layout="total, sizes, prev, pager, next, jumper"
   :total="user_data.total"
   @size-change="handleSizeChange"
   @current-change="handleCurrentChange"

   class="table"
  />

</el-card>

<!-- 添加用户对话框 -->

<el-dialog v-model="dialogFormVisible" title="添加用户" width="500" :before-close="addFormReset">
    <el-form :model="addUser_form" :rules="user_rules" ref="addFormRef">

      <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="addUser_form.name" autocomplete="off" />
      </el-form-item>

      <el-form-item label="密码" :label-width="formLabelWidth" prop="pwd">
        <el-input v-model="addUser_form.pwd" autocomplete="off" />
      </el-form-item>

      <el-form-item label="确认密码" :label-width="formLabelWidth" prop="real_pwd">
        <el-input v-model="addUser_form.real_pwd" autocomplete="off" />
      </el-form-item>

      <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
        <el-input v-model="addUser_form.nick_name" autocomplete="off" />
      </el-form-item>
      
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="addUser_form.phone" autocomplete="off" />
      </el-form-item>
      
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="addUser_form.email" autocomplete="off" />
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addFormReset">取消</el-button>
        <el-button type="primary" @click="addUser(addFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>


  <!-- 编辑用户对话框 -->
  <el-dialog v-model="EditdialogFormVisible" title="编辑用户" width="500" >
    <el-form :model="editUser_form" :rules="edit_rules" ref="editFormRef">

      <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="editUser_form.name" autocomplete="off"  disabled />
      </el-form-item>

  

      <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
        <el-input v-model="editUser_form.nick_name" autocomplete="off" />
      </el-form-item>
      
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="editUser_form.phone" autocomplete="off" />
      </el-form-item>
      
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="editUser_form.email" autocomplete="off" />
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="EditdialogFormVisible=false">取消</el-button>
        <el-button type="primary" @click="editUser(editFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 删除用户对话框 -->
  <el-dialog v-model="deletedialogFormVisible" title="删除用户" width="500" >
   <span>确认删除 账号:[{{ remove_user.name }}]
                昵称：[{{remove_user.nick_name}}]
                用户吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deletedialogFormVisible=false">取消</el-button>
        <el-button type="primary" @click="deleteUser">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 重置密码对话框 -->
  <el-dialog v-model="resetdialogVisible" title="重置密码" width="500" >
   <span>确认重置 账号:[{{ reset_user.name }}]
                昵称：[{{reset_user.nick_name}}]
                用户的密码吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetdialogVisible=false">取消</el-button>
        <el-button type="primary" @click="resetPassword">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>


<script setup>
import { ArrowRight ,Search,CirclePlus} from '@element-plus/icons-vue'
import { onMounted, ref,reactive, unref } from 'vue'
import api from '@/api/index.js'
import { ElMessage } from 'element-plus';

let pagesize=ref([1,2,5,10])

  onMounted(
    ()=>{
      
      get_user_list()
    }
  )


// 添加用户表单信息
  const addUser_form=reactive({
    name:'',
    pwd:'',
    real_pwd:'',
    phone:'',
    email:'',
    nick_name:''
  })
//编辑用户表单信息 注意使用let声明 这是一个变量 可以被修改
  let editUser_form=reactive({
    name:'',
    phone:'',
    email:'',
    nick_name:''
  })
//删除用户表单信息
  let remove_user=reactive({
    id:null,
    name:null,
    nick_name:null
  })
//重置密码表单信息
let reset_user=reactive({
    id:null,
    name:null,
    nick_name:null
})
//修改用户控制器
  const handleEdit=(index,row)=>{
    EditdialogFormVisible.value=true
    //el-form=edit_form 将当前行数据传入表单
    // editUser_form=row 第一种写法 有bug

    //从数据库读取用户信息赋值给编辑表单 row.id获取当前行id
    api.get_user_by_id(row.id).then(res=>{
      // editUser_form=res.data.data 这样写会有延迟 因为数据匹配花时间
      editUser_form.name=res.data.data.name
      editUser_form.phone=res.data.data.phone
      editUser_form.nick_name=res.data.data.nick_name
      editUser_form.email=res.data.data.email
      // console.log(res)
    })
    user_id.value=row.id //采用ref的方式 选择使用value进行赋值
  }
//删除用户控制器
  const handleDelete=(index,row)=>{
    remove_user.id=row.id,
    remove_user.name=row.name,
    remove_user.nick_name=row.nick_name
    deletedialogFormVisible.value=true
  }
//用户重置密码控制器
  const handleRest=(index,row)=>{
    reset_user.id=row.id,
    reset_user.name=row.name,
    reset_user.nick_name=row.nick_name
    resetdialogVisible.value = true
}

  // 自定义的确认密码校验规则
  // 它接受三个参数：rule（验证规则）、value（待验证的值）和callback（验证完成后调用的回调函数）
  const validatePass=(rule,value,callback)=>{
    if(value===''){
      callback(new Error('请输入确认密码'))
      // 如果输入的确认密码为空，则调用回调函数，并传递一个包含错误消息 '请输入确认密码' 的错误对象。
    }
    else if(value!==addUser_form.real_pwd){
      callback(new Error("2次密码不一致"))
      // 如果输入的确认密码与实际密码不相等，则同样调用回调函数，并传递一个包含错误消息 "2次密码不一致" 的错误对象。
    }
    else{
      callback()
      //  如果确认密码符合规则，则调用回调函数，但不传递任何参数，表示验证通过。
    }
  }
  //验证手机号
  const validatePhone=(rule,value,callback)=>{
    if(value===''){
      callback(new Error('请输入手机号'))
    }
    else if(!/^1[3456789]\d{9}$/.test(value)){
      callback(new Error('手机号格式不正确'))
    }
    else{
      callback()
    }
  }
  //验证邮箱
   const validateEmail = (rule, value,
callback) => {
   if (value === '') {
       callback(new Error('请输入邮箱'))
  } else if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/i.test(value)) {
     callback(new Error("邮箱格式不正确!"))
  } else {
     callback()
    }
    }

  //添加用户验证信息
  const user_rules=reactive({
    name:[
      {required:true,message:'请输入用户名',trigger:'blur'},
      {min:3,max:5,message:'长度3—5个字符',trigger:'blur'}
    ],
    pwd:[
      {required:true,message:'请输入密码',trigger:'blur'},
      {min:3,max:5,message:'长度3—5个字符',trigger:'blur'}
    ],
    real_pwd:[
    {required:true,message:'请确认密码',trigger:'blur'},
    {validator:validatePass,trigger:'blur'} //设置校验规则
    ],
    nick_name:[
      {required:true,message:'请输入昵称',trigger:'blur'},
      {min:1,max:5,message:'长度1-5个字符',trigger:'blur'}
    ],
    phone:[
    { validator: validatePhone, trigger:'blur' }
    ],
    email:[
    { validator: validateEmail, trigger:'blur' }
    ]

  })


  // 利用reactive实现双向绑定
  const user_data=reactive({
    tableData:[],
    total:0,
    pageNum:1,
    pageSize:2,
    queryName:''
  })

  //获取数据库的用户列表
  const get_user_list=()=>{
    //内置的参数 我们想改变数据时通过外部函数去改变user_data中pnum psize
    let params={
        'pnum':user_data.pageNum,
        'psize':user_data.pageSize,
         //搜索框将数据传入user_list.queryName中
        'name':user_data.queryName
      }
      api.get_users({params}).then(res=>{
        console.log(res)
        user_data.tableData=res.data.data.data
        user_data.total=res.data.data.total
      })
  }

  //查询用户
  const searchUser=()=>{
    //初始化页码
    user_data.pageNum=1
    //搜索框将数据传入user_list.queryName中
    get_user_list()
  }
  
  //分页控制器
  const handleSizeChange = (val) => {
    //修改页面大小
  user_data.pageSize=val
  //重新渲染数据
  get_user_list()
  }
const handleCurrentChange = (val) => {
  //渲染页码
  user_data.pageNum=val
  //重新渲染数据
  get_user_list()
  }


  // 重置addUser表单
  const addFormReset=()=>{
    let formRef=unref(addFormRef)
    formRef.resetFields()
    dialogFormVisible.value = false
    
  }

  //添加用户操作实现
  const addUser=(formRef)=>{
    formRef.validate((valid)=>{
      if(valid){
        console.log("验证通过 可以提交")
        api.add_user(addUser_form).then(res=>{
          //根据相应结果进行处理
          if(res.data.status==200){
            ElMessage({
              message:res.data.msg,
              type:'success'
            })
          }
          else{
            ElMessage.warning(res.data.msg)
          }
        })
        //重置表单
        addFormReset()
        //刷新数据
        get_user_list()
      }
      else{
        console.log('验证失败')
        return false
      }
    }

    )
  }
  

  //提交修改用户表单操作实现
  const editUser=(editFormRef)=>{
 
    api.edit_user(user_id.value,editUser_form).then(res=>{
      //根据相应结果进行处理
      if(res.data.status==200){
        ElMessage({
          message:res.data.msg,
          type:'success'
        })
        get_user_list()
        EditdialogFormVisible.value=false
        
      }
      else{
        ElMessage.warning (res.data.msg)
      }
    })
  }

//删除用户操作实现
  const deleteUser=()=>{
    //删除用户的接口调用
    api.delete_user(remove_user.id).then(res=>{
      if(res.data.status==200){
        ElMessage({
          message:res.data.msg,
          type:'success',
        })
        deletedialogFormVisible.value=false
        get_user_list()
      }else{
        ElMessage.warning(res.data.msg)
      }
    })

  }
  const resetPassword=()=>{
    //重置密码的接口调用
    api.reset_user_password(reset_user.id).then(res=>{
      if(res.data.status==200){
        ElMessage({
          message:res.data.msg,
          type:'success',
        })
        resetdialogVisible.value=false
        get_user_list()
      }else{
        ElMessage.warning(res.data.msg)
      }
    })
  }

  const addFormRef=ref(null)
  const formLabelWidth = '95px'
  const small = ref(false)
  const background = ref(false)
  const disabled = ref(false)
  const dialogFormVisible = ref(false)
  const editFormRef = ref(null)
  let resetdialogVisible=ref(false)
  let EditdialogFormVisible=ref(false)
  let user_id=ref(0)
  let deletedialogFormVisible=ref(false)
</script>

<style scoped>
 .box-card{
  margin-top: 20px;
  }
 .table{
  margin-top: 30px;
  }
  .input-with-select{
    margin-top: 30px;
  }
  .adduser-button{
    margin-top: 43px;
  }
</style>